package com.boot.cluster.worker.selector;

import com.boot.cluster.worker.bean.Node;
import com.boot.cluster.worker.bean.TaskSplitterInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/***
 * 任务平均分配器
 * @author lichunwen
 *
 */
public class AverageSelector implements Selector<Node, TaskSplitterInfo> {

    private static Logger logger = LoggerFactory.getLogger(AverageSelector.class);

    @Override
    public String name() {
        return null;
    }

    @Override
    public Map<Node, List<TaskSplitterInfo>> selector(List<Node> address, List<TaskSplitterInfo> infos) {
        if ((address == null) || address.isEmpty() || (infos == null) || infos.isEmpty()) {
            logger.warn("Cluster state anomaly");
            return new HashMap<>();
        }
        Map<Node, List<TaskSplitterInfo>> map = new HashMap<>();
        int size = address.size();
        int length = infos.size();
        int div = length / size;
        int page = (length % size) != 0 ? (div + 1) : div;
        for (int t = 1; t <= page; t++) {
            int k = 0;
            for (int j = 0; j < size; j++) {
                int index = ((t - 1) * size) + k;
                if (index >= length) {
                    break;
                }
                if (map.containsKey(address.get(j))) {
                    map.get(address.get(j)).add(infos.get(index));
                } else {
                    List<TaskSplitterInfo> tm = new ArrayList<>();
                    tm.add(infos.get(index));
                    map.put(address.get(j), tm);
                }
                k++;
            }
        }
        return map;
    }

}
